/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package maindatart.metadata;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import maindatart.util.C3p0Source;
import maindatart.util.MainDataSQLBuilder;

/**
 *
 * @author 丁丁
 * 
 * 主数据元数据管理类
 * 
 */
public class MDMetaDataService {
    
    MetaDataDao dao = new MetaDataDao();
    
    /**
     * 增加一个对主数据的元数据描述
     * @param mdmd 
     */
    public void add(MainDataMetaDataEntity mdmd)throws Exception {
        try {
            dao.addMainDataMetaData(mdmd);
        } catch (SQLException ex) {
            Logger.getLogger(MDMetaDataService.class.getName()).log(Level.SEVERE, null, ex);
            throw (Exception)ex;
        }
    }
    /**
     * 删除一个对主数据元数据的描述
     * @param mdmd 
     */
    public void delete(MainDataMetaDataEntity mdmd){
        try {
            dao.dellMainDataMetaDatas(mdmd);
        } catch (SQLException ex) {
            Logger.getLogger(MDMetaDataService.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    /**
     * 根据元数据描述，生成主数据存储表
     * @param mdmd 
     */
    public void regMainData(MainDataMetaDataEntity mdmd) throws Exception {
        String sql = MainDataSQLBuilder.makeTableSQL(mdmd);
        
        Connection cn = C3p0Source.getConnection();
        Statement d = null;
        try {
            d = cn.createStatement();
            d.execute(sql);
            
            int count = mdmd.getCarbonDataCount();
            
            for(int i = 0 ;i < count;i ++){
                sql = MainDataSQLBuilder.makeCorbonTableSQL(mdmd,Integer.toString(i));
                d.execute(sql);
            }
            
        } catch (SQLException ex) {
            Logger.getLogger(MDMetaDataService.class.getName()).log(Level.SEVERE, null, ex);
            throw new Exception(ex);
        }finally{
            C3p0Source.realseSource(null, d, cn);
        }
        
    }
    
    /**
     * 根据注册的主数据名称获取主数据的元数据描述
     * 
     *  名称为主数据英文名称
     * @param mainDataName
     * @return 
     */
    public MainDataMetaDataEntity getMainDataMetaDataByName(String mainDataName) throws Exception{
        
        return dao.getMainDataMetaDataByEnName(mainDataName);
    }
            
    public List<MainDataMetaDataEntity> getAllRegMainData() throws Exception{
        return dao.getAll();
    }
    
    private String getID(){
        UUID uuid = UUID.randomUUID();   
        return uuid.toString();
    }
    
    public static void main(String[] args){
        MDMetaDataService service = new MDMetaDataService();
        System.out.println(service.getID());
        
        
    }
}
